import {defineComponent, onMounted, reactive, ref} from 'vue'
import SearchFrom from "./comp/SearchForm"
import {header, operateBtn as operateBtn1, toolBar} from "./data"
import {storeToRefs} from "pinia";
import TableList from "@/components/TableList";
import Dialog from "./comp/Dialog";
import {ElMessage, ElMessageBox} from "element-plus";
import {CategoriesStore} from "@/stores/categories";
import {formatDateTime, overflowHidden} from "@/utils/utils";
import {useRouter} from "vue-router";

export default defineComponent({
    props:{
        is_user: {
            type: Boolean,
            default: false
        }
    },
    setup(props) {
        const router = useRouter()
        // 用categories数据仓库
        const categories_store = CategoriesStore()
        // 显示弹出框
        const visible = ref(false)
        // 是否为详情页面
        const isDetail = ref(false)
        const diaTitle = ref("")
        const total = ref(0)

        const operateBtn = ref(operateBtn1)
        // 从仓库中获取数据
        let {categoriesList, categoriesInfo} = storeToRefs(categories_store)
        // 搜索参数
        const queryParams = reactive({
            categories_name: undefined,
            type_id: undefined,
            pageNum: 1,
            pageSize: 10,
            is_user: props.is_user
        })

        const currentId = ref(undefined)

        // 获取众筹项目列表
        const handleQuery = async () => {
            const res = props.is_user ? await categories_store.getMyCategoriesList(queryParams) : await categories_store.getCategoriesList(queryParams)
            total.value = res.total
        }

        // 改变页码大小
        const handleSizeChange = async (val) => {
            queryParams.pageSize = val
            await handleQuery()
        }

        // 改变当前页
        const handleCurrentChange = async (val) => {
            queryParams.pageNum = val
            await handleQuery()
        }

        // 点击编辑
        const handleEdit = async (id) => {
            await categories_store.getCategoriesInfo(id)
            currentId.value = id
            visible.value = true
            diaTitle.value = "审核众筹项目"
            isDetail.value = false
        }

        // 点击查看详情
        const handleDetail = async (id) => {
            // 将该资讯的浏览量+1
            const code = await categories_store.updateInformationRecord(id, 'view')
            if (code === 0) {
                // 跳转值详情页面
                router.push({name: 'categoryDetails', query: {id}})
            }
        }

        // 关闭弹出框
        const closeDia = () => {
            categoriesInfo.value = {}
            visible.value = false
        }

        // 保存弹出框
        const saveDia = async () => {
            const data = {status: categoriesInfo.value.status}
            const res = await categories_store.updateCategories(currentId.value, data)
            closeDia()
            if (res) {
                ElMessage.success("修改成功")
                await handleQuery()
            } else {
                ElMessage.error("修改失败")
            }
        }

        // 删除众筹项目
        const handleDelete = (id) => {
            ElMessageBox.confirm(
                props.is_user ? '是否确认撤销该众筹项目？' : '是否确认删除该众筹项目？',
                '提示',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(async () => {
                await categories_store.deleteCategories(id)
                ElMessage.success(props.is_user ? "撤销成功" : "删除成功")
                await handleQuery()
            })
                .catch((err) => {
                    ElMessage.error("取消删除")
                })
        }

        const changeValue = (name, value) => {
            categoriesInfo.value[name] = value
        }

        const formatStatus = (status) => {
            if(status === 0) return <el-tag>待审核</el-tag>
            if(status === 1) return <el-tag class="ml-2" type="success">同意</el-tag>
            if(status === 2) return <el-tag class="ml-2" type="danger">已驳回</el-tag>
            if(status === 3) return <el-tag class="ml-2" type="warning">已过期</el-tag>
        }

        const handleBtn = (name, row) => {
            if (name === 'view') {
                handleDetail(row.id)
            } else if (name === 'del') {
                handleDelete(row.id)
            } else if (name === 'status') {
                handleEdit(row.id)
            }
        }

        // 如果是用户页面
        if(props.is_user){

            operateBtn.value = operateBtn.value.filter(item => item.name !== 'status')
            // 把删除按钮改为撤销
            operateBtn.value.forEach(item => {
                if(item.name === 'del'){
                    item.label = '撤销'
                }
            })
        }

        onMounted(async () => {
            await handleQuery()
        })


        return () => {
            return (
                <div className="app-container">
                    <SearchFrom
                        is_user={props.is_user}
                        queryParams={queryParams}
                        handleQuery={handleQuery}/>
                    <TableList
                        tableData={categoriesList.value}
                        handleSizeChange={handleSizeChange}
                        handleCurrentChange={handleCurrentChange}
                        handleBtn={handleBtn}
                        header={header}
                        toolBar={toolBar}
                        operateBtn={operateBtn.value}
                        total={total.value}
                        v-slots={{
                            imgUrl: (row) => {
                                return <el-image
                                    style={{width: '100px', height: '100px'}}
                                    src={row.imgUrl}
                                    zoom-rate={1.2}
                                    fit={'cover'}
                                    preview-src-list={[row.imgUrl]}
                                    preview-teleported={true}
                                />
                            },
                            describe: (row) => {
                                return <el-tooltip content={row.describe} placement="bottom" popper-class="tooltip"
                                                   effect="customized">
                                    <p>{overflowHidden(row.describe)}</p>
                                </el-tooltip>
                            },
                            expected_amount: (row) => {
                                return row.expected_amount + "元"
                            },
                            amount_raised: (row) => {
                                return row.amount_raised + "元"
                            },
                            nick_name: (row) => {
                                return row.user_info.nick_name
                            },
                            type_name: (row) => {
                                return row.type_info.type_name
                            },
                            end_time: (row) => {
                                return formatDateTime(row.end_time)
                            },
                            love: (row) => {
                                return row.record_info.love + "次"
                            },
                            status: (row) => {
                                return formatStatus(row.status)
                            },
                            view: (row) => {
                                return row.record_info.view + "次"
                            },
                            createdAt: (row) => {
                                return formatDateTime(row.createdAt)
                            },
                            updatedAt: (row) => {
                                return formatDateTime(row.updatedAt)
                            }
                        }}
                    />
                    <Dialog
                        diaTitle={diaTitle.value}
                        visible={visible}
                        diaForm={categoriesInfo.value}
                        isDetail={isDetail.value}
                        changeValue={changeValue}
                        saveDia={saveDia}
                        closeDia={closeDia}
                    />
                </div>
            )
        }
    }
})